package db

import (
	"fmt"
	"net/url"
	"ruanGongKeShe16Zu/model"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	drivername := viper.GetString("datasource.drivername")
	host := viper.GetString("datasource.host")
	passwordort := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	loc := viper.GetString("datasource.loc")

	//"root:123456@tcp(127.0.0.1:3306)/demo_user?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s",
		username, password, host, passwordort, database, charset, url.QueryEscape(loc))

	db, err := gorm.Open(mysql.New(mysql.Config{DriverName: drivername, DSN: dsn}), &gorm.Config{})
	if err != nil {
		panic("failed to connect database, err:" + err.Error())
	}
	db.AutoMigrate(&model.User{})
	db.AutoMigrate(&model.Category{})
	DB = db
	return db
}

func GetDB() *gorm.DB {
	return DB
}
